package lijiale.project.util;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import com.mysql.cj.xdevapi.JsonArray;

public class FmtRequest {// 提炼参数映射成对象的过程

	/**
	 * 网页参数名和实体类属性名一致时 根据请求的参数情况反射到实体类对象中
	 * 
	 * @param <T>   需要反射生成的实体类对象
	 * @param req   请求对象
	 * @param clazz 需要反射的实体类的类的描述
	 * @return T
	 */
	public static <T> T parseModel(HttpServletRequest req, Class<T> clazz) {
		T obj = null;
		try {
			obj = clazz.newInstance(); 
			
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
		Map<String, String[]> map = req.getParameterMap();
		for (Entry<String, String[]> entry : map.entrySet()) {
			String name = entry.getKey();// key是参数名，value是参数名
			if ("action".equals(name)) // "action"参数用不到。
				continue;
			try {// 通过参数名来进行反射,反射出来实体类中的属性字段对应的对象
				Field field = clazz.getDeclaredField(name);
				field.setAccessible(true);// 取消访问限制
				field.set(obj, entry.getValue()[0]);// 把传过来的参数映射到实体类当中
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return obj;
	}

	/**
	 * 网页参数名和实体类属性名不一致时 根据映射关系反射生成实体类对象
	 * 
	 * @param <T>
	 * @param req    请求对象
	 * @param clazz  需要反射的实体类的类的描述
	 * @param fields key=属性名 value=参数名
	 * @return
	 */
	public static <T> T parseModel(HttpServletRequest req, Class<T> clazz, Map<String, String> fields) {
		T obj = null;
		try {
			obj = clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
		for (Entry<String, String> entry : fields.entrySet()) {
			String name = entry.getKey();
			String val = req.getParameter(entry.getValue());
			try {
				Field field = clazz.getDeclaredField(name);
				field.setAccessible(true);// 取消访问限制
				field.set(obj, val);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	public static void write(Writer wr, String val) {
		try {
			wr.write(val);
			wr.flush();
			wr.close();
			wr = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public static void write(Writer wr, Object val) {
		if(val instanceof Collection<?>) {//如果传进来的是个线性的集合
			write(wr,new JSONArray((Collection<?>) val).toString());
		}else if(val instanceof String) {
			write(wr,val.toString());
		}else if(val instanceof Map<?,?>){
			write(wr,new JSONObject((Map<?,?>)val).toString());
		}else {
			write(wr,new JSONObject(val).toString());
		}
	}

}
